package game;


import java.io.IOException;
import java.net.Socket;
import java.util.List;

import javax.swing.JApplet;

import technicalservices.error.ErrorHandler;
import application.config.Config;
import application.config.Config.Status;
import domain.server.IGameProtocol;
import domain.users.User;

/**
 * The GameModel class is the super class for each games (applets). By extending
 * GameModel the game can communicate with the ServerProtocol via the interface
 * IGameProtocol
 */
public abstract class GameModel extends JApplet implements IGameProtocol {

	private transient Socket socket;
	protected User player;
	private List<User> players;
	private int currentPlayer = 0;

	public GameModel() {
		/*
		try {
			this.socket = new Socket("localhost", Config.PROTOCOL_PORT);
		} catch (Exception e) {
			ErrorHandler.getInstance().showError("The server is currently offline, so only single-player mode available");
		}
		*/
	}

	public void setPlayers(List<User> players2) {
		this.players = players2;
	}
	
	public void setPlayer(User player) {
		this.player = player;
	}

	public User getCurrentPlayer() {
		return players.get(currentPlayer);
	}
	
	public void alternatePlayer() {
		currentPlayer = (currentPlayer == 0 ? 1 : (currentPlayer == 1 ? 2 : 0));
	}
	
	@Override
	public abstract void startGame();
	
	@Override
	public void sendObject(Object object) {
		
	}

	@Override
	public Object receiveObject() {
		return null;
	}

	@Override
	public void sendCommand(Status command) {
	}

	@Override
	public int receiveCommand() {
		return 0;
	}

	@Override
	public void joinGame(IGameData gameData) {
		sendCommand(Config.Status.CLIENT_CONNECTED);
	}

	@Override
	public void quitGame() {
		try {
			if (socket != null) {
				socket.close();
			}
		} catch (IOException ex) {
			ErrorHandler.getInstance().showError("The socket couldn't be closed.");
		}
	}

	@Override
	public void spectateGame(IGameData gameData) {
		ErrorHandler.getInstance().showError("You can't spectate matches yet.");
	}

}
